<template>
	<el-dialog title="地图标记" v-model="visible" :close-on-click-modal="false" width="75%" draggable destroy-on-close>
		<div class="relative w-full h-[600px]">
			<div class="pickerBox">
				<el-input type="text" prefixIcon="search" v-model="keyword" @keyup.enter="handleSearchAddress" id="tipInput" placeholder="请输入关键词搜索" />
				<div class="pickerList" v-show="searchList.length">
					<div v-for="item in searchList" :key="item.id" class="truncate pickerList-item" :title="item.formattedAddress" @click="handlePicker(item)">
						{{ item.formattedAddress }}
					</div>
				</div>
			</div>
			<div ref="wrapRef" id="container" class="w-full h-full"></div>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="confirm">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
import { ref, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useMessage } from '/@/hooks/message';
const emits = defineEmits(['confirm']);
const props = defineProps({
	width: {
		type: String,
		default: '100%',
	},
	height: {
		type: String,
		default: '100%',
	},
	zoom: {
		type: Number,
		default: 5,
	},
	latitude: {
		type: Number,
		default: 101.4327,
	},
	longitude: {
		type: Number,
		default: 33.37086,
	},
	styleId: {
		type: String,
	},
});

const visible = ref(false);
const wrapRef = ref<HTMLDivElement | null>(null);
const keyword = ref();
const locationInfo = reactive({
	lng: '',
	lat: '',
	address: '',
	building: '',
});
const searchList = ref<any[]>([]);
let map: any;
let marker: any;
let infoWindow: any;
let Geocoder: any;
async function initMap() {
	(window as any)._AMapSecurityConfig = { securityJsCode: '3e6cf3d22e1f6b3b31087119fd73d0ea' };
	AMapLoader.load({
		key: '61a2206220e92f8131d82b95b4c37918', // 申请好的Web端开发者Key，首次调用 load 时必填
		version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
		plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
		// AMapUI: {
		// 	version: '1.1',
		// 	plugins: ['overlay/SimpleMarker'],
		// },
	})
		.then((AMap) => {
			map = new AMap.Map('container', {
				resizeEnable: true,
				// 设置地图容器id
				viewMode: '3D', // 是否为3D地图模式
				zoom: 4.3, // 初始化地图级别
				center: [103.732739, 35.275814], // 初始化地图中心点位置
			});
			Geocoder = new AMap.Geocoder();
			map.on('click', onMapClick);
			// 标记
			marker = new AMap.Marker();
			// 信息窗
			infoWindow = new AMap.InfoWindow({
				offset: new AMap.Pixel(0, -30),
			});
			// @ts-ignore
			// (AMapUI as any)?.loadUI(['misc/PoiPicker'], function (PoiPicker) {
			// 	let poiPicker = new PoiPicker({
			// 		//city:'北京',
			// 		input: 'tipInput',
			// 	});
			// 	//初始化poiPicker
			// 	poiPickerReady(poiPicker);
			// });
		})
		.catch((e) => {
			console.log(e);
		});
}
function onMapClick(e: any) {
	Geocoder.getAddress(e.lnglat, (status: string, result: any) => {
		if (status === 'complete' && result.regeocode) {
			const item = Object.assign({}, result.regeocode, { location: e.lnglat });
			setMarkerAndInfo(item);
		} else {
			useMessage().error('根据经纬度查询地址失败');
		}
	});
	// map.setCenter(marker.getPosition());
}
// 输入地址查询
function handleSearchAddress() {
	Geocoder.getLocation(keyword.value, (status: string, result: any) => {
		if (status === 'complete' && result.geocodes.length) {
			searchList.value = result.geocodes;
		} else {
			searchList.value = [];
			useMessage().error('根据经纬度查询地址失败');
		}
	});
}
const handlePicker = (item: any) => {
	setMarkerAndInfo(item);
	map.setCenter(marker.getPosition());
	map.setFitView();
};
function setMarkerAndInfo(item: any) {
	locationInfo.address = item.formattedAddress;
	locationInfo.lat = item.location.lat;
	locationInfo.lng = item.location.lng;
	locationInfo.building = item.addressComponent.building;
	marker.setMap(map);
	infoWindow.setMap(map);
	marker.setPosition(item.location);
	infoWindow.setPosition(item.location);
	infoWindow.setContent(
		'位置信息: <pre>经度：' +
			locationInfo.lng +
			'</pre><pre>纬度：' +
			locationInfo.lat +
			'</pre>' +
			'<pre>建筑物：' +
			locationInfo.building +
			'</pre>' +
			'<pre>详细地址：' +
			locationInfo.address +
			'</pre>'
	);
	infoWindow.open(map, marker.getPosition());
}
function poiPickerReady(poiPicker: any) {
	(window as any).poiPicker = poiPicker;

	//选取了某个POI
	poiPicker.on('poiPicked', function (poiResult: any) {
		const poi = poiResult.item,
			info = {
				name: poi.name,
				location: poi.location.toString(),
				address: poi.address,
				district: poi.district,
			};
		locationInfo.address = info.district + info.address + info.name;
		locationInfo.lat = poi.location.lat;
		locationInfo.lng = poi.location.lng;
		marker.setMap(map);
		infoWindow.setMap(map);

		marker.setPosition(poi.location);
		infoWindow.setPosition(poi.location);

		infoWindow.setContent('位置信息: <pre>' + info.district + info.address + '</pre><pre>' + info.name + '</pre>');
		infoWindow.open(map, marker.getPosition());

		map.setCenter(marker.getPosition());
		map.setFitView();
	});
}
// 打开弹窗
const openDialog = () => {
	visible.value = true;
	initMap();
};
const confirm = () => {
	visible.value = false;
	emits('confirm', locationInfo);
};
onUnmounted(() => {
	map?.destroy();
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style lang="scss" scoped>
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
.amap_lib_placeSearch .poibox.highlight {
	background-color: #cae1ff;
}

.amap_lib_placeSearch .poi-more {
	display: none !important;
}
:deep(.amap-ui-poi-picker-sugg-list .sugg-item) {
	font-size: 12px;
	line-height: 14px;
}
.pickerBox {
	position: absolute;
	z-index: 9999;
	top: 20px;
	left: 20px;
	width: 300px;
	.pickerList {
		margin-top: 2px;
		background-color: #fff;
		border: 1px solid #ccc;
		border-bottom: none;
		// padding: 12px;
		cursor: pointer;
		max-height: 360px;
		overflow-y: auto;
		width: 300px;
		font-size: 12px;
		.pickerList-item {
			padding: 6px 10px;
			// margin-top: 6px;
			border-bottom: 1px solid #ccc;
		}
		:hover {
			background-color: #cae1ff;
		}
	}
}
</style>
